package 恰好型滑动窗口

func subarraysWithKDistinct(nums []int, k int) int {
	left1, left2, cnt1, cnt2 := 0, 0, 0, 0
	diff1 := map[int]int{}
	diff2 := map[int]int{}
	for right, num := range nums {
		diff1[num]++
		diff2[num]++
		for len(diff1) >= k && left1 <= right {
			l := nums[left1]
			diff1[l]--
			if diff1[l] == 0 {
				delete(diff1, l)
			}
			left1++
		}
		cnt1 += left1
		for len(diff2) >= k+1 && left2 <= right {
			l := nums[left2]
			diff2[l]--
			if diff2[l] == 0 {
				delete(diff2, l)
			}
			left2++
		}
		cnt2 += left2
	}
	return cnt1 - cnt2
}
